<template>
  <div>
    <el-upload
      :action="computedAction"
      :on-success="handleSuccess"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      multiple
      :limit="element.options.length"
      :headers="element.options.headers"
      :on-exceed="handleExceed"
      :file-list="processedFileList"
      :disabled="element.options.disabled"
      :style="{'width': element.options.width}"
    >
      <div v-if="!preview">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">{{ element.options.tip }}</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'FileUpload',
  // eslint-disable-next-line vue/require-prop-types
  props: ['element', 'preview', 'dataModel'],
  data() {
    return {
      fileListTmp: []
    }
  },
  computed: {
    computedAction() {
      // 检查action是否包含占位符
      if (this.element.options.action && this.element.options.action.includes('ipaddress:port')) {
        // 如果包含占位符，使用环境变量替换
        return process.env.VUE_APP_BASE_API + '/api/v1/public/uploadFile'
      }
      // 如果action已经是完整URL且不包含占位符，直接使用
      if (this.element.options.action && this.element.options.action.startsWith('http')) {
        return this.element.options.action
      }
      // 否则拼接环境变量中的API基础地址
      return process.env.VUE_APP_BASE_API + this.element.options.action
    },
    processedFileList() {
      if (!this.dataModel || !Array.isArray(this.dataModel)) {
        return []
      }
      return this.dataModel.map(file => {
        return {
          ...file,
          name: this.removeUuidPrefix(file.name)
        }
      })
    }
  },
  methods: {
    removeUuidPrefix(fileName) {
      if (!fileName) return ''
      // 匹配UUID格式：8-4-4-4-12位十六进制字符，后跟下划线
      const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_/i
      return fileName.replace(uuidPattern, '')
    },
    handleRemove(file, fileList) {
      this.fileListTmp = fileList
      this.$emit('fileList', fileList)
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多允许上传 ${this.element.options.length} 个文件。`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定要移除 ${file.name}？`)
    },
    handleSuccess(response, file, fileList) {
      // 处理上传成功后的URL
      let uploadUrl = response.data || response.url
      if (uploadUrl && !uploadUrl.includes('http')) {
        const baseAPI = process.env.VUE_APP_BASE_API || 'http://localhost:8002/api/v1'
        const serverUrl = baseAPI.replace('/api/v1', '')
        const normalizedUrl = uploadUrl.startsWith('/') ? uploadUrl : '/' + uploadUrl
        uploadUrl = serverUrl + normalizedUrl
      }

      this.fileListTmp = fileList.map(f => ({
        uid: f.uid,
        name: f.name,
        url: f.url || uploadUrl
      }))
      this.$emit('fileList', this.fileListTmp)
    }
  }
}
</script>

<style scoped>

</style>
